import Footer from '@/components/Footer';

import {
  confirmSelectLoginOrganization,
  listSelectLoginOrganization,
} from '@/services/api/api-login';
import { setToken } from '@/utils/token';
import { CheckCard } from '@ant-design/pro-components';
import { LoginForm } from '@ant-design/pro-form';
import { Avatar, message, Space, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import { Helmet, history, useLocation, useModel } from 'umi';

export default (): React.ReactNode => {
  const { initialState, setInitialState } = useModel('@@initialState');

  let location = useLocation();

  const parse = (str = window.location.search) => {
    const reg = /([^?&=]+)=([^&]+)/g; // 分组捕获 两个子组
    const params = {};
    str.replace(reg, (_, k, v) => (params[k] = v));
    return params;
  };

  const [selectLoginOrganizations, setSelectLoginOrganizationsState] =
    useState<LoginData.LoginListSelectOrganizationVo[]>();

  const loadListSelectLoginOrganizationData = async (accountId: string) => {
    // 登录
    const response = await listSelectLoginOrganization({ accountId });
    if (response.code === 0) {
      console.log(response.data);
      setSelectLoginOrganizationsState(response.data);
    }
  };

  const [selectId, setSelectIdState] = useState<string>();

  useEffect(() => {
    const { accountId } = parse(location.search) as { accountId: string };

    // //小小的验证码
    // if (select === undefined && (select as string).length === 13) {
    //   history.push('/user/login');
    // }

    loadListSelectLoginOrganizationData(accountId);
  }, []);

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        overflow: 'auto',
        backgroundImage:
          "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
        // backgroundImage: '/page_login_layout_bg_img_4.png',
        backgroundSize: '100% 100%',
      }}
    >
      <Helmet>
        <title>{'选择单位 - 重庆市新闻选题管理平台'}</title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.png" />}
          title="重庆市新闻选题管理平台"
          subTitle={'重庆市委宣传部'}
          submitter={
            selectId
              ? {
                  searchConfig: {
                    submitText: '登录',
                  },
                  submitButtonProps: {
                    size: 'large',
                    style: {
                      width: '100%',
                    },
                  },
                }
              : false
          }
          onFinish={async () => {
            if (!selectId) {
              message.warning('请选择登录单位');
              return false;
            }

            const response = await confirmSelectLoginOrganization({
              combineId: selectId,
            });

            if (response.code === 0) {
              setToken(response.data.satoken);
              const userInfo = await initialState?.fetchUserInfo?.();
              if (userInfo) {
                setInitialState({
                  ...initialState,
                  currentUser: userInfo,
                });
                setTimeout(() => {
                  history.push('/');
                }, 100);
              }
            }
          }}
        >
          <CheckCard.Group
            onChange={(value) => {
              setSelectIdState(value?.toString());
            }}
          >
            {selectLoginOrganizations?.map((item) => (
              <CheckCard
                bordered={false}
                key={item.id}
                disabled={item.state === 0}
                avatar={<Avatar size="large" src={item.organizationAvatar} />}
                title={
                  <Space size={[0, 'small']} wrap>
                    {item.organizationCascaders.map((e) => (
                      <Tag key={e.id}>{e.name}</Tag>
                    ))}
                  </Space>
                }
                description={item.loginTime === null ? '首次登录' : `上次登录：${item.loginTime}`}
                value={item.id}
              />
            ))}
          </CheckCard.Group>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
